package egovframework.npqs.pqi.mobile.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.sds.BizAppLauncher.gov.aidl.GovController.IGovCallback;

import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsonparser.PlaceOfficerThread;
import egovframework.npqs.pqi.mobile.jsonparser.PlaceOfficerThread.PlaceOfficerThreadCallback;

/* 검역 결과 등록 화면*/
public class PlaceOfficerActivity extends Activity implements PlaceOfficerThreadCallback{
	private TextView titleTxt, navigation;	// 상단 타이틀
	private AppStatus myapp;
	private String userNm, duplSn;
	private Context context;
	private ListView listView;
	private OfficerListAdapter officerAdapter;
	private PlaceOfficerThread officerThread;
	private EditText offEdit, editProdName;
	private ImageButton searchBtn, btnHome, btn_exit;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("현장검역관");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_place_officer);
		
		Intent intent = getIntent();
		userNm = intent.getStringExtra("userNm");
	/*	if(null!=intent.getStringExtra("duplSn")){
			duplSn = intent.getStringExtra("duplSn");
			Toast.makeText(context, "duplSn: "+duplSn, Toast.LENGTH_SHORT).show();
		}*/
		init();
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("현장검역관");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		offEdit = (EditText)findViewById(R.id.edit_prod_name);
		//offEdit.setText("5123");
		listView = (ListView)findViewById(R.id.officer_list);
		officerAdapter = new OfficerListAdapter();
		
		editProdName = (EditText)findViewById(R.id.edit_prod_name);
		editProdName.setText(userNm);
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		searchBtn=(ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/*searchOfficeResult();*/
				myapp.utilm.InputKeybordHidden(context, offEdit);
				searchOfficeResult();
			}
		});
		
		dateLoad();
	}
	
	private void searchOfficeResult(){
		/*dateLoad();*/
		
		if(offEdit.getText().toString().equals("")){
			myapp.utilm.ShowDialog(PlaceOfficerActivity.this, "실패", "ID 또는 이름을 입력하세요.", 20);
		}else{
			dateLoad();
		}
	}
	
	private void dateLoad(){
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "검색";
		threadStart();
		
	}
	
	public void threadStart(){
		if("검색".equals(temp)){
    		officerThread = new PlaceOfficerThread(context, this, offEdit.getText().toString()
    				, myapp.getLoginItem().getOffCd(), AppStatus.getmUserId());
    		officerThread.start();
    	}
	}
	
	@Override
	public void OnPlaceOfficerCompleted(boolean isNetworkConntected,
			boolean results, String message) {
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(results) {
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}
	
	@Override
	public void OnPlaceOfficerError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				
				officerAdapter.notifyDataSetChanged();
				listView.setAdapter(officerAdapter);
				
				/*if(myapp.getArrPlaceOfficerItem().size() == 1){
					returnToActivity();
				}else{
					officerAdapter.notifyDataSetChanged();
					listView.setAdapter(officerAdapter);	
				}*/
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				officerAdapter.notifyDataSetChanged();
				listView.setAdapter(officerAdapter);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	private void returnToActivity(){
		Intent intent = new Intent();
		intent.putExtra("userNm", myapp.getArrPlaceOfficerItem().get(0).getUserNm());
		intent.putExtra("userSn", myapp.getArrPlaceOfficerItem().get(0).getUserSn());
		intent.putExtra("allInsttNm", myapp.getArrPlaceOfficerItem().get(0).getAllInsttNm());
		
		setResult(1, intent);
		finish();
	}
	
	class OfficerListAdapter extends BaseAdapter {
		TextView officerName, officerNumber;

		@Override
		public int getCount() {
			Log.i("getCount", "getCount");
			return myapp.getArrPlaceOfficerItem().size();
		}

		@Override
		public Object getItem(int position) {
			Log.i("getItem", "getItem");
			return myapp.getArrPlaceOfficerItem().get(position);
		}

		@Override
		public long getItemId(int position) {
			Log.i("getItemId", "getItemId");
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_place_officer_item, parent, false);
    		}
			
			officerName = (TextView)convertView.findViewById(R.id.officer_name);
			officerNumber = (TextView)convertView.findViewById(R.id.officer_number);
			
			officerName.setText(myapp.getArrPlaceOfficerItem().get(position).getUserNm());
			officerNumber.setText(myapp.getArrPlaceOfficerItem().get(position).getUserSn());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			/*if(duplSn.equals(myapp.getArrPlaceOfficerItem().get(position).getUserSn())){
				myapp.utilm.ShowDialog(PlaceOfficerActivity.this, "실패", "같은 검역관은 선택 할 수 없습니다.", 20);
			}*/
			Intent intent = new Intent();
			intent.putExtra("userNm", myapp.getArrPlaceOfficerItem().get(position).getUserNm());
			intent.putExtra("userSn", myapp.getArrPlaceOfficerItem().get(position).getUserSn());
			intent.putExtra("allInsttNm", myapp.getArrPlaceOfficerItem().get(0).getAllInsttNm());
			setResult(1, intent);
			finish();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
}